const crypto = require("crypto");
const axios = require("axios");
const {readini} = require("./operFile.js");

const dingdingSend = (texts) => {
  //   // 读取配置文件
  let conf = readini("./dingdingSendConfig.ini")
  if (conf.code == 300) return
  let config = conf.data
  const keys = Object.keys(config.dingdingSend);
  for (let key of keys) {
    // 输出内容
    const webhookUrl = config.dingdingSend[key]["webhook"];
    const secret = config.dingdingSend[key]["secret"];
    // const webhookUrl =
    //   "https://oapi.dingtalk.com/robot/send?access_token=a2153d89144caf54dd0cdc7cdfb0f3419685420fad221dac18224d2ecae55c64";
    // const secret =
    //   "SEC70939a9b6eb3eaf9a49fe53b3ab9d7401914b16e5d784af28b8d55eb8f9fabc6";
    const timestamp = Date.now();

    // 生成签名
    const signString = `${timestamp}\n${secret}`;
    const sign = crypto
      .createHmac("sha256", secret)
      .update(signString)
      .digest("base64");

    // 将签名和时间戳添加到 Webhook URL
    const signedWebhookUrl = `${webhookUrl}&timestamp=${timestamp}&sign=${encodeURIComponent(
      sign
    )}`;

    // const message = {
    //   msgtype: "text",
    //   text: {
    //     content: texts,
    //   },
    // };
    const message = {
      msgtype: "markdown",
      markdown: {
        title: "消息",
        text: texts,
        // text: "# 这是一个标题\n这是一个 **Markdown** 消息\n- 列表项 1\n- 列表项 2",
      },
    };

    axios
      .post(signedWebhookUrl, message)
      .then((response) => {
        // console.log("send success ：", response.data);
      })
      .catch((error) => {
        // console.error("send error ： ", error);
      });
  }
};

module.exports = {
  dingdingSend,
};
